package com.community.web.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.community.common.exception.NeusoftException;
import com.community.common.result.ResultCodeEnum;
import com.community.model.entity.OrderDetail;
import com.community.model.entity.Orders;
import com.community.model.entity.PortalWalletLog;
import com.community.model.entity.Wallet;
import com.community.web.user.mapper.CartsMapper;
import com.community.web.user.mapper.GoodsStoreMapper;
import com.community.web.user.service.*;
import com.community.web.user.mapper.OrdersMapper;
import com.community.web.user.vo.OrdersQueryVo;
import com.community.web.user.vo.OrdersVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

/**
* @author admin
* @description 针对表【orders】的数据库操作Service实现
* @createDate 2024-07-02 10:56:56
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
    implements OrdersService{

    @Autowired
    private OrderDetailService detailService;

    @Autowired
    private CartsService cartsService;

    @Autowired
    private WalletService walletService;

    @Autowired
    private PortalWalletLogService walletLogService;


    @Autowired
    private CartsMapper cartsMapper;

    @Autowired
    private GoodsStoreMapper goodsStoreMapper;

    @Autowired
    private OrdersMapper mapper;

    @Transactional
    @Override
    public Orders add(Long userId, List<Long> cartIdList) {
        //获取orderDetail
        List<OrderDetail> list = cartsMapper.selectListByIds(cartIdList);
        //随机生成订单号
        UUID uuid = UUID.randomUUID();
        String uuidStr = uuid.toString().replaceAll("-", "");
        //向orderDetail添加订单号,同时计算订单总金额
        BigDecimal total = new BigDecimal(0);
        for (OrderDetail item :
                list) {
            item.setOrderNo(uuidStr);
            total = total.add(item.getGoodsPrice());
            //减少库存
            goodsStoreMapper.subStock(item);
        }
        //批量添加
        detailService.saveBatch(list);
        //添加order
        Orders orders = new Orders();
        orders.setUserId(userId.intValue());
        orders.setOrderNo(uuidStr);
        orders.setTotalPrice(total);
        orders.setOrderState(-1);
        orders.setDeliveryType(1);
        super.save(orders);
        //删除购物车对应条目
        cartsService.removeBatchByIds(cartIdList);
        return orders;
    }

    @Override
    public IPage<OrdersVo> pageList(Page<OrdersVo> page, OrdersQueryVo queryVo) {
        return mapper.pageList(page, queryVo);
    }

    @Override
    public OrdersVo selectDetailList(String ordersNo) {
        return mapper.selectDetailList(ordersNo);
    }

    @Transactional
    @Override
    public void payment(Long userId, Orders orders) {
        //获取订单信息
        LambdaQueryWrapper<Orders> ordersQueryWrapper = new LambdaQueryWrapper<>();
        ordersQueryWrapper.eq(Orders::getOrderNo, orders.getOrderNo());
        ordersQueryWrapper.eq(Orders::getOrderState, -1);
        Orders orders1 = super.getOne(ordersQueryWrapper);
        if (orders1 == null){
            throw new NeusoftException(ResultCodeEnum.PARAM_ERROR);
        }
        //判断余额是否足够
        LambdaQueryWrapper<Wallet> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Wallet::getUserId, userId);
        Wallet wallet = walletService.getOne(queryWrapper);
        if (orders1.getTotalPrice().compareTo(wallet.getWalletBalance()) > 0){
            throw new NeusoftException(ResultCodeEnum.NOT_ENOUGH);
        }
        //修改余额
        wallet.setWalletBalance(wallet.getWalletBalance().subtract(orders1.getTotalPrice()));
        walletService.saveOrUpdate(wallet);
        //支付成功后修改订单状态
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Orders::getOrderNo, orders.getOrderNo());
        updateWrapper.set(Orders::getOrderState, 1);
        updateWrapper.set(Orders::getPaymentType,orders.getPaymentType());
        updateWrapper.set(Orders::getPaymentSubtype, orders.getPaymentSubtype());
        super.update(updateWrapper);
        //操作记录
        PortalWalletLog walletLog = new PortalWalletLog();
        walletLog.setWalletId(wallet.getId());
        walletLog.setAmount(orders1.getTotalPrice());
        walletLog.setType(1);
        walletLog.setState(1);
        walletLogService.addLog(walletLog);

    }
}




